<template>
  <el-dialog
    v-model="visible"
    :title="`维度详情 - ${dimensionData.dimension_name || ''}`"
    width="1200px"
    destroy-on-close
    :before-close="handleBeforeClose"
  >
    <div v-loading="props.loading" class="detail-container">
      <!-- 基本信息 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">基本信息</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="维度名称">
            {{ dimensionData.dimension_name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="维度代码">
            <span class="monospace-text">{{
              dimensionData.dimension_code || "-"
            }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="所属模板" :span="2">
            {{ dimensionData.template_name || "-" }}
            <el-tag 
              v-if="dimensionData.template_is_active !== undefined"
              :type="dimensionData.template_is_active ? 'success' : 'danger'"
              size="small"
              class="ml-2"
            >
              {{ dimensionData.template_is_active ? "启用" : "禁用" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模板代码">
            {{ dimensionData.template_code || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="模板版本">
            {{ dimensionData.template_version || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="维度描述" :span="2">
            {{ dimensionData.dimension_description || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ dimensionData.created_at || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ dimensionData.updated_at || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 评分规则 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">评分规则</span>
        </template>
        <el-descriptions :column="4" border>
          <el-descriptions-item label="最大分值">
            {{ dimensionData.max_score || 0 }} 分
          </el-descriptions-item>
          <el-descriptions-item label="权重系数">
            {{ dimensionData.weight || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="显示顺序">
            {{ dimensionData.display_order || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="dimensionData.is_enabled ? 'success' : 'info'"
              size="small"
            >
              {{ dimensionData.is_enabled ? "已启用" : "已禁用" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div class="score-range">
          加权得分范围: 0 ~
          {{ (dimensionData.max_score || 0) * (dimensionData.weight || 0) }} 分
          ({{ dimensionData.max_score || 0 }} × {{ dimensionData.weight || 0 }})
        </div>
      </el-card>

      <!-- 使用情况 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">使用情况</span>
        </template>
        <div class="usage-info">
          <div class="usage-count">
            <el-tag type="info" size="large">
              {{ dimensionData.template_count || 0 }} 个模板使用
            </el-tag>
          </div>

          <el-divider>使用该维度的模板列表</el-divider>
          
          <el-table
            v-if="
              dimensionData.using_templates &&
              dimensionData.using_templates.length > 0
            "
            :data="dimensionData.using_templates"
            border
            size="small"
            max-height="250"
          >
            <el-table-column
              prop="template_name"
              label="模板名称"
              min-width="180"
            ></el-table-column>
            <el-table-column
              prop="template_code"
              label="模板代码"
              min-width="180"
            ></el-table-column>
            <el-table-column prop="is_active" label="状态" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="row.is_active ? 'success' : 'danger'"
                  size="small"
                >
                  {{ row.is_active ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div
            v-if="
              !dimensionData.using_templates ||
              dimensionData.using_templates.length === 0
            "
            class="no-usage-data"
          >
            <el-empty description="该维度尚未被任何模板使用" :image-size="80" />
          </div>
        </div>
      </el-card>

      <!-- 配置详情 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">配置详情</span>
        </template>
        <el-tabs>
          <el-tab-pane label="数据源配置">
        <div class="config-section">
          <div class="config-type">
                类型:
                {{ getDataSourceTypeName(dimensionData.data_source_type) }} ({{
                  dimensionData.data_source_type || "-"
                }})
          </div>
              <pre class="config-content">
                {{ formatJson(dimensionData.data_source_config) }}
              </pre>
          <el-button 
            type="text" 
            size="small"
                @click="copyConfig(dimensionData.data_source_config)"
            class="copy-btn"
          >
            复制配置
          </el-button>
        </div>
          </el-tab-pane>
          <el-tab-pane label="计算配置">
        <div class="config-section">
          <div class="config-type">
                类型:
                {{ getCalculationTypeName(dimensionData.calculation_type) }} ({{
                  dimensionData.calculation_type || "-"
                }})
          </div>
              <pre class="config-content">
                {{ formatJson(dimensionData.calculation_config) }}
              </pre>
          <el-button 
            type="text" 
            size="small"
                @click="copyConfig(dimensionData.calculation_config)"
            class="copy-btn"
          >
            复制配置
          </el-button>
        </div>
          </el-tab-pane>
          <el-tab-pane label="聚合配置">
        <div class="config-section">
          <div class="config-type">
                模式:
                {{ getAggregationModeName(dimensionData.aggregation_mode) }} ({{
                  dimensionData.aggregation_mode || "-"
                }})
          </div>
              <pre class="config-content">
                {{ formatJson(dimensionData.aggregation_config) }}
              </pre>
              <div
                v-if="dimensionData.aggregation_mode === 'priority'"
                class="config-description"
              >
            说明: 按优先级取值，优先取风险最高的状态
          </div>
          <el-button 
            type="text" 
            size="small"
                @click="copyConfig(dimensionData.aggregation_config)"
            class="copy-btn"
          >
            复制配置
          </el-button>
        </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button type="primary" @click="handleCopy">复制维度</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, computed } from "vue";
import { ElMessage, ElNotification } from "element-plus";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  dimensionId: {
    type: [String, Number],
    default: "",
  },
  dimensionData: {
    type: Object,
    default: () => ({}),
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "view-usage", "copy"]);

// 响应式数据
const visible = ref(props.modelValue);
const dimensionData = computed(() => props.dimensionData || {});

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
  visible.value = val;
  }
);

// 格式化JSON显示
const formatJson = (data: any) => {
  if (!data) return "{}";
  try {
    return JSON.stringify(data, null, 2);
  } catch (e) {
    return JSON.stringify(data);
  }
};

// 获取数据源类型名称
const getDataSourceTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single_table: "单表查询",
    multi_table: "多表关联",
    external_api: "外部接口",
  };
  return typeMap[type] || type || "-";
};

// 获取计算类型名称
const getCalculationTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    level_mapping: "级别映射",
    weighted_sum: "加权求和",
    weighted: "加权计算",
    threshold: "阈值判断",
    custom: "自定义公式",
  };
  return typeMap[type] || type || "-";
};

// 获取聚合模式名称
const getAggregationModeName = (mode: string) => {
  const modeMap: Record<string, string> = {
    max: "最大值",
    avg: "平均值",
    average: "平均值",
    sum: "求和",
    priority: "优先级",
  };
  return modeMap[mode] || mode || "-";
};

// 复制配置
const copyConfig = (config: any) => {
  try {
    const text = JSON.stringify(config, null, 2);
    navigator.clipboard.writeText(text);
    ElNotification.success({
      title: "成功",
      message: "配置已复制到剪贴板",
      duration: 2000,
    });
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 复制维度
const handleCopy = () => {
  if (dimensionData.value.id) {
    emit("copy", dimensionData.value.id);
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭前处理
const handleBeforeClose = () => {
  emit("update:modelValue", false);
  return true;
};
</script>

<style scoped lang="scss">
.detail-container {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}

.ml-2 {
  margin-left: 8px;
}

.score-range {
  margin-top: 15px;
  padding: 8px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
}

.usage-info {
  padding: 5px 0;
}

.usage-count {
  margin-bottom: 15px;
}

.no-usage-data {
  padding: 20px;
  text-align: center;
}

.config-section {
  position: relative;
}

.config-type {
  margin-bottom: 10px;
  font-weight: 500;
  color: #1d2129;
}

.config-content {
  background-color: #fafafa;
  padding: 12px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 13px;
  line-height: 1.5;
  overflow-x: auto;
  max-height: 250px;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.config-description {
  margin-top: 10px;
  padding: 8px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  color: #52c41a;
}

.copy-btn {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0;
  font-size: 12px;
}
</style>
